package com.ay.proxy.reflect.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 相对于静态代理
 * @author Ackles
 */
public class DynamicProxyDemo {
	public static void main(String[] args) {
		Dynamic dynamic = new DynamicImpl();
		Dynamic proxy = (Dynamic) getProxy(dynamic);
		proxy.doDynamic();
	}

	@SuppressWarnings("unchecked")
	private static <T> T getProxy(T dynamic) {
		ClassLoader loader = dynamic.getClass().getClassLoader();
		Class<?>[] interfaces = dynamic.getClass().getInterfaces();
		InvocationHandler h = new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				System.out.println("before doDynamic");
				Object result = method.invoke(dynamic, args);
				System.out.println("after doDynamic, result : " + result);
				return result;
			}
		};
		Object proxy = Proxy.newProxyInstance(loader, interfaces, h);
		return (T) proxy;
	}
}

interface Dynamic {
	void doDynamic();
}

class DynamicImpl implements Dynamic {
	@Override
	public void doDynamic() {
		System.out.println("DynamicImpl.doDynamic");
	}
}